#include "stdafx.h"
#include "ThreadLock.h"

//-------------------CCriSecLock-----------------------------
//-------------------------------------------------------------
#if defined(FOREST_PLATFORM_WINDOWS)

CCriSecLock::CCriSecLock()
	: m_pCS(NULL)
{
	m_pCS = new CRITICAL_SECTION;
	if(m_pCS)
	{
		InitializeCriticalSection(m_pCS);
	}
};

CCriSecLock::~CCriSecLock()
{
	if(m_pCS)
	{
		delete m_pCS;
		m_pCS = NULL;
	}
}

void CCriSecLock::Lock() const
{
	if(m_pCS)
	{
		EnterCriticalSection(m_pCS);
	}
}

void CCriSecLock::Unlock() const
{
	if(m_pCS)
	{
		LeaveCriticalSection(m_pCS);
	}
}

#endif




//-------------------CMutexLock------------------------------
//-------------------------------------------------------------
CMutexLock::CMutexLock()
{
#if defined(FOREST_PLATFORM_WINDOWS)
	m_Mutex = ::CreateMutex(NULL,FALSE,NULL);

#elif defined(FOREST_PLATFORM_LINUX)
	pthread_mutex_init(&m_Mutex,NULL);
#endif
}


CMutexLock::~CMutexLock()
{
#if defined(FOREST_PLATFORM_WINDOWS)
	::CloseHandle(m_Mutex);

#elif defined(FOREST_PLATFORM_LINUX)
	pthread_mutex_destroy(&m_Mutex);
#endif
}


void CMutexLock::Lock() const
{
#if defined(FOREST_PLATFORM_WINDOWS)
	DWORD dw = WaitForSingleObject(m_Mutex,INFINITE);

#elif defined(FOREST_PLATFORM_LINUX)
	pthread_mutex_lock(&m_Mutex);
#endif
}


void CMutexLock::Unlock() const
{
#if defined(FOREST_PLATFORM_WINDOWS)
	::ReleaseMutex(m_Mutex);


#elif defined(FOREST_PLATFORM_LINUX)
	pthread_mutex_unlock(&m_Mutex);
#endif
}


//-------------------CScopeLock---------------------------------
//-------------------------------------------------------------
CScopeLock::CScopeLock(const IThreadLock* pThreadMutex)
	: m_pThreadMutex(pThreadMutex)
{
	if(m_pThreadMutex)
	{
		m_pThreadMutex->Lock();
	}
}


CScopeLock::~CScopeLock()
{
	if(m_pThreadMutex)
	{
		m_pThreadMutex->Unlock();
	}
}
